package com.hyacinth.chache;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 使用
 * @author zhangfb
 * @version 1.0.0.1
 * @since JDK 1.8
 */
public class SafeConcurrentHashCacheBySync<K, V> implements ConcurrentMapCache<K, V> {

    private final ConcurrentHashMap<K, V> cacheMap = new ConcurrentHashMap<>();

    public synchronized Object getCache(K keyValue,String ThreadName){
        System.out.println("ThreadName getCache=============="+ThreadName);
        Object value=null;
        //从缓存获取数据
        value=cacheMap.get(keyValue);

        try {
            // 延迟，创造并发条件
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //如果没有的话，把数据放到缓存
        if(value==null){
            return putCache(keyValue,ThreadName);
        }
        return value;
    }

    public Object putCache(K keyValue, String ThreadName){
        System.out.println("ThreadName 执行业务数据并返回处理结果的数据（访问数据库等）=============="+ThreadName);
        //可以根据业务从数据库获取等取得数据,这边就模拟已经获取数据了
        @SuppressWarnings("unchecked")
        V value=(V) "dataValue";
        //把数据放到缓存
        cacheMap.put(keyValue, value);
        return value;
    }
}
